<template>
  <avue-form
    ref="formData"
    v-model="formData"
    :option="formOptions"
    @submit="getLogList"
  >
  </avue-form>

  <avue-crud
    ref="crudRef"
    :option="option"
    :data="tableData"
    :page="pageSearch"
    @size-change="sizeChange"
    @current-change="currentChange"
  >
<!--    @expand-change="handleChange"-->
    <template #handleCode="scope">
      <div>{{ scope.row.handleCode == '200' ? '成功' : '失败' }}</div>
    </template>
    <template #log="scope">
      <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
    </template>
    <template #expand>
      <avue-tabs
        v-model="tabs"
        :option="tabOption"
        @change="handleTabChange"
        style="padding: 0 30px"
      />
      <div style="padding: 0 30px">
        <avue-crud
          :option="option2"
        >

        </avue-crud>
      </div>
    </template>
    <template #menuForm>
      <el-button type="primary">查询</el-button>
    </template>
  </avue-crud>
</template>

<script setup lang="ts">
import { reactive, ref, defineProps, onMounted, watch, nextTick } from 'vue';
import { listLog } from "@job/api/job/log";

const props = defineProps({
  tab: {
    type: String,
    default: 'tab1'
  },
  row: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['changeTab']);

const option = ref(
  {
    border: true,
    index: true,
    indexLabel: '序号',
    indexWidth: 70,
    stripe: true,
    highlightCurrentRow: true,
    align: 'center',
    menu: false,
    selection: false,
    // height: 400,
    showSummary: false,
    addBtn: false,
    editBtn: false,
    delBtn: false,
    header: false,
    expand: true,
    rowKey: 'id',
    column: [
      { label: '任务名称', prop: 'name', align: 'center' },
      { label: '执行状态', prop: 'handleCode' },
      { label: '任务执行id', prop: 'jobGroup' },
      { label: '执行日志', prop: 'log' },
      { label: '成功/失败记录', prop: 'records' },
      { label: '开始时间', prop: 'triggerTime' },
      { label: '结束时间', prop: 'handleTime' },
      { label: '耗时',  prop: 'elapsedTime' }
    ]
  }
)
const dateRange = ref([]);
let pageSearch = reactive({
  logStatus:'',
  jobId:'',
  jobGroup: '',
  orderBy: 'TRIGGER_TIME',
  sortDirect: 'DESC',
  total: 0, // 总页数
  pageNum: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
});

const option2 = ref(
  {
    border: true,
    index: true,
    indexLabel: '序号',
    indexWidth: 70,
    stripe: true,
    highlightCurrentRow: true,
    align: 'center',
    menu: false,
    selection: false,
    height: 400,
    showSummary: false,
    addBtn: false,
    editBtn: false,
    delBtn: false,
    header: false,
    expand: false,
    rowKey: 'id',
    column: [
      { label: '状态', prop: 'status', align: 'center' },
      { label: '节点id', prop: 'id' },
      { label: '节点名称', prop: 'name' },
      { label: '读取', prop: 'read' },
      { label: '插入', prop: 'insert' },
      { label: '更新', prop: 'update' },
      { label: '删除', prop: 'delete' },
      { label: '开始时间',  prop: 'triggerTime' },
      { label: '结束时间',  prop: 'handleTime' }
    ]
  }
)

const tabs = ref(props.tab);

const formOptions = ref({
  labelWidth: '50',
  submitBtn: true,
  submitText: '查询',
  emptyBtn: false,
  labelPosition: 'right',
  menuPosition: 'center',
  menuSpan: 2,
  column: [
    { label: '开始', prop: 'triggerTime', type: 'datetime',  span: 5, valueFormat: 'YYYY-MM-DD HH:mm:ss' },
    { label: '结束', prop: 'handleTime', type: 'datetime', span: 5, valueFormat: 'YYYY-MM-DD HH:mm:ss' },
  ]
})

const tabOption = ref({
  column: [{
    label: '执行步骤',
    prop: 'tab1',
  }, {
    label: '汇总统计',
    prop: 'tab2',
  }, {
    label: '成功数据',
    prop: 'tab3',
  }, {
    label: '失败数据',
    prop: 'tab4',
  }]
});

onMounted(() => {
  getLogList()
})

const tableData = ref([])
const formData = reactive({
  triggerTime: '',
  handleTime: ''
})

const handleChange = (row, expandList) => {
  // console.log('expandList',expandList)
  // if (expandList.length) {
  //   option1.value.expandRowKeys = [];
  //   if (row) {
  //     option1.value.expandRowKeys.push(row.id);
  //   }
  // } else {
  //   option1.value.expandRowKeys = [];
  // }
}

const parseTime = (timeStr?: string | null): number => {
  if (!timeStr) return 0;
  try {
    const normalizedTime = timeStr.includes(':') ? timeStr : `${timeStr} 00:00:00`;
    return new Date(normalizedTime).getTime();
  } catch (e) {
    console.error('时间解析失败:', e);
    return 0;
  }
};

// 查询调度日志列表
const getLogList = (form, done) => {
  console.log(111)
  if (typeof done !== 'function') {
    done = () => {};
  }
  pageSearch.jobId = props.row?.jobInfoDTO?.id;
  // pageSearch = {
  //   ...pageSearch,
  //   ...form
  // }
  let params = {
    ...pageSearch,
    ...form
  }
  console.log('params',params)
  listLog(params).then(response => {
    pageSearch.total = response.data.total;
    tableData.value = response.data.list.map(item => {
      const start = parseTime(item.triggerTime);
      const end = parseTime(item.handleTime);
      const elapsed = start > 0 && end > 0 ? Math.round((end - start) / 1000) : 0;

      return {
        ...item,
        name: props.row.ktrTaskName,
        elapsedTime: elapsed + '秒'
      };
    });
    done()
  });
}

const sizeChange = (pageSize) => {
  pageSearch.pageSize = pageSize;
  getLogList(formData, () => {});

}
const currentChange = (current) => {
  pageSearch.pageNum = current;
  getLogList(formData, () => {});

}

const handleView = (row) => {
  emit('changeTab', {row, tab: 'tab2'})
}

const handleTabChange = (e) => {
  console.log('e', e);
  tabs.value = e;
}
</script>

<style scoped lang="scss">
::v-deep .el-form-item__label {
  position: static !important;
}
::v-deep .el-form-item {
  display: flex !important;
}
::v-deep .avue-crud .el-table .el-form-item__content {
  padding-left: 50px
}
</style>